<template>
    <div style="padding:0 37px 0 44px" class="main-container-div">
        <div class="breadcrumb-father">
            <div class="new-breadcrumb">
                <router-link :to="{path:'/welcome'}">
                    <img src="../../assets/imgs/Home.png" alt="">
                </router-link>
                <span>{{$t('trade.transaction')}}</span>
                <span class="arrow">></span>
                <span>{{$t('trade.MerchantRef1')}}</span>
            </div>
        </div>
        <div class="card-table">
            <div class="card-table-title">
                <svg aria-hidden="true" class="svg-icon svg-title-icon">
                    <use xlink:href="#icon-jiaoyiliushui"></use>
                </svg>
                <span>{{ $t('trade.MerchantRef1') }}</span>
            </div>
            <!--搜索输入框-->
            <div class="search">
                <div class="search-input">

                    <div class="date-wrapper">
                        <label for="">{{$t('search.SelectBeginTime')}}</label>
                        <div class="date-line"></div>
                        <el-date-picker :editable=false clearable value-format="yyyy-MM-dd HH:mm:ss" class="filter-item" type="datetime" v-model="searchOrderData.startDate"></el-date-picker>
                    </div>

                    <div>
                        <label for="">{{$t('search.SelectEndTime')}}</label>
                        <el-date-picker :editable=false clearable value-format="yyyy-MM-dd HH:mm:ss" class="filter-item" type="datetime" v-model="searchOrderData.endDate"></el-date-picker>
                    </div>

                    <div class="date-wrapper">
                        <label for="">{{ $t('trade.Amount') }}</label>
                        <div class="date-line"></div>
                        <el-input type="text" clearable oninput="this.value=this.value.replace(/[^\d.]/g,'');this.value=this.value.replace(/\.{2,}/g,'.');this.value=this.value.replace('.','$#$').replace(/\./g,'').replace('$#$','.');this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');if(this.value>500000){this.value=500000}" :placeholder="$t('trade.Minimum')" v-model="searchOrderData.minMoney" @keyup.enter.native="handleFilter(0)" class="time-input"></el-input>
                    </div>

                    <div>
                        <label for=""></label>
                        <el-input type="text" clearable oninput="this.value=this.value.replace(/[^\d.]/g,'');this.value=this.value.replace(/\.{2,}/g,'.');this.value=this.value.replace('.','$#$').replace(/\./g,'').replace('$#$','.');this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');if(this.value>500000){this.value=500000}" v-model="searchOrderData.maxMoney" :placeholder="$t('trade.Maximum')" @keyup.enter.native="handleFilter(0)" class="time-input"></el-input>
                    </div>

                    <div>
                        <label for="">{{ $t('search.RefNo1') }}</label>
                        <el-input v-model="searchOrderData.outTradeNo" clearable :maxlength=27 @keyup.enter.native="handleFilter(0)"></el-input>
                    </div>

                    <div v-if=" userType !== '1' ">
                        <label for="">{{ $t('search.MerchantName2') }}</label>
                        <el-input v-model="searchOrderData.name" clearable :maxlength=100 @keyup.enter.native="handleFilter(0)"></el-input>
                    </div>

                    <div v-if=" userType !== '1' ">
                        <label for="">{{ $t('trade.merchantNumber') }}</label>
                        <el-input v-model="searchOrderData.subMchId" clearable :maxlength=100 @keyup.enter.native="handleFilter(0)"></el-input>
                    </div>
                    <div v-if="userType != '10' && userType != '1' ">
                        <label for="">{{$t('search.AgentName2')}}</label>
                        <el-select v-model="searchOrderData.distributorId" popper-class="el-select-custom" filterable clearable @keyup.enter.native="handleFilter(0)" :placeholder="$t('placeH.All')">
                            <el-option v-for="(item,index) in queryAgentData" :key="index" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </div>

                    <div>
                        <label for="">{{ $t('button.Shops1') }}</label>
                        <el-input v-model="searchOrderData.shopName" clearable :maxlength=100 @keyup.enter.native="handleFilter(0)"></el-input>
                    </div>

                    <div>
                        <label for="">{{$t('search.TransactionType1')}}</label>
                        <el-select :placeholder="$t('placeH.All')" popper-class="el-select-custom" @keyup.enter.native="handleFilter(0)" v-model="searchOrderData.trade" clearable class='filter-item condition'>
                            <el-option value=1 :label="$t('trade.Payment')"></el-option>
                            <el-option value=2 :label="$t('trade.Refund')"></el-option>
                        </el-select>
                    </div>

                    <div>
                        <label for="">{{ $t('search.TransactionStatus') }}</label>
                        <el-select :placeholder="$t('placeH.All')" popper-class="el-select-custom" @keyup.enter.native="handleFilter(0)" v-model="searchOrderData.setllment" clearable class='filter-item condition'>
                            <el-option value=1 :label="$t('search.SettledDone')"></el-option>
                            <el-option value=2 :label="$t('search.NotSettled')"></el-option>
                        </el-select>
                    </div>
                    <div>
                        <label for="">{{$t('search.TransactionCompleted2')}}</label>
                        <el-select :placeholder="$t('placeH.All')" popper-class="el-select-custom" @keyup.enter.native="handleFilter(0)" v-model="searchOrderData.tradeState" clearable class='filter-item condition'>
                            <el-option value=1 :label="$t('search.Yes')"></el-option>
                            <el-option value=2 :label="$t('search.No')"></el-option>
                        </el-select>
                    </div>

                    <!-- 改成微信支付与支付宝 -->
                    <div>
                        <label for="">{{ $t("search.Channel") }}</label>
                        <el-select :placeholder="$t('placeH.All')" popper-class="el-select-custom" @keyup.enter.native="handleFilter(0)" v-model="searchOrderData.walletType" clearable class='filter-item condition'>
                            <el-option v-if=" companyId == '1' " value=0 :label="$t('search.WechatRMBWallet')"></el-option>
                            <el-option v-if=" companyId == '1' " value=1 :label="$t('search.WechatHKDWallet')"></el-option>
                            <el-option v-if=" companyId == '1' " value='2,3' :label="$t('search.Alipay')"></el-option>
                            <!-- 支付宝 澳洲大商户模式 -->
                            <el-option v-if=" companyId == '1' " value=4 :label="$t('trade.Unionpay')"></el-option>

                            <el-option v-if=" companyId == '2' " value='0,1' :label="$t('search.WechatRMBWallet')"></el-option>
                            <el-option v-if=" companyId == '2' " value=2 :label="$t('search.Alipay')"></el-option>
                            <!-- 支付宝 澳洲大商户模式 -->
                        </el-select>
                    </div>

                    <div class="search-btn-group">
                        <el-button class="blue-btn mini2-btn" @click="handleFilter(0)">{{$t('button.search')}}</el-button>
                        <el-button class="blue-btn mini2-btn" @click='delSelect()'>{{$t('button.Reset')}}</el-button>
                    </div>
                </div>
            </div>
            <!--交易流水表单-->
            <template>
                <div class="table-border">
                    <div class="search-result-head">
                        <span> {{ searchInfo }} </span>
                        <span style="float:right;">
                            <a href="javascript:void(0)" @click='export2Excel()' :title="$t('button.SaveResult')">
                                <icon-svg icon-class="daochu"></icon-svg>
                            </a>
                            <a href="javascript:void(0)" @click="refresh()" :title="$t('button.Refresh')">
                                <icon-svg icon-class="shuaxin" id="refresh_icon"></icon-svg>
                            </a>
                        </span>
                    </div>
                    <!-- 交易流水表 -->
                    <el-table border :data="tradeDatas" height=535 @cell-mouse-enter="showHandle" @cell-mouse-leave="hiddenHandle" v-loading="loading" :element-loading-text="$t('button.loading')" element-loading-background="rgba(255, 255, 255, 1)">
                        <el-table-column type="index" fixed :label="$t('index.Number')" width="60"></el-table-column>
                        <el-table-column prop="merchantName" :label="$t('search.MerchantName1')" class-name="title_name" width="135"> </el-table-column>
                        <el-table-column prop="merchantNumber" :label="$t('trade.merchantNumber')" width="150"> </el-table-column>
                        <el-table-column prop="merid" :label="$t('search.SubAccountNo')" v-if=" userType==='9' || userType==='11' || userPhone === '13501189583' || userPhone === '15018955912' || userPhone === '15219441946' " width="180"> </el-table-column>
                        <el-table-column prop="shopName" :label="$t('button.Shops1')" width="150" :formatter='judgeShopName' show-overflow-tooltip></el-table-column>
                        <el-table-column prop="addedDate" :label="$t('trade.Time')" width="180"></el-table-column>
                        <el-table-column prop="walletType" :label="$t('search.Channel')" width="120" :formatter='judgeTradeWay' show-overflow-tooltip></el-table-column>
                        <el-table-column prop="money" :label="$t('trade.Amount')" width="120" :formatter='judgeMoney'></el-table-column>
                        <el-table-column prop="poundage" :label="$t('trade.fee')" width="160" :formatter='judgePoundage'></el-table-column>
                        <el-table-column prop="collectedAmount" :label="$t('trade.receivableAmount')" width="160" :formatter='judgeCollected'></el-table-column>
                        <el-table-column prop="payType" :label="$t('trade.TransactionType')" width="100" :formatter='judgePayType'></el-table-column>
                        <el-table-column prop="payType" :label="$t('trade.PaymentMethod')" width="160" :formatter='judgePayMethod'></el-table-column>
                        <el-table-column prop="tradeState" :label="$t('search.TransactionCompleted1')" width="160" :formatter='judgePayResult'></el-table-column>
                        <el-table-column prop="setllment" :label="$t('search.TransactionStatus1')" width="110" :formatter='judgeSetllment'></el-table-column>
                        <el-table-column prop="deviceType" :label="$t('trade.Device')" width="160" :formatter='judgeDevice'></el-table-column>
                        <el-table-column prop="deviceNo" :label="$t('trade.DeviceID')" width="140" :formatter='judgeDeviceNo' show-overflow-tooltip></el-table-column>
                        <el-table-column prop="cashierName" :label="$t('trade.Staff')" width="120" :formatter='judgeStaff'></el-table-column>
                        <el-table-column prop="outTradeNo" :label="$t('search.RefNo1')" width="230"></el-table-column>
                        <el-table-column prop="outRefundNo" :label="$t('trade.OriginalTransactionNumber')" width="245" :formatter="judgeOutRefundNo"></el-table-column>
                        <el-table-column prop="no" :label="$t('trade.MerchantTransactionNumber')" width="265" :formatter="judgeTransactionNo"></el-table-column>
                        <el-table-column prop="detail" :label="$t('trade.Remarks')" width="150"></el-table-column>
                        <el-table-column fixed="right" class-name="animate_td handle-hidden-2">
                            <template slot-scope="scope">
                                <a class="svg-link-class" :title="$t('trade.Remarks')" @click="showRemarks(scope.row.detail)">
                                    <svg aria-hidden="true" class="svg-icon svg-action-icon">
                                        <use xlink:href="#icon-beizhu"></use>
                                    </svg>
                                </a>
                                <a class="svg-link-class" v-if=" userType=='1' " :title="$t('trade.Refund')" @click="showRefund(scope.row.outTradeNo,scope.row.tradeState,scope.row.addedDate,scope.row.outRefundNo,scope.row.walletType)">
                                    <svg aria-hidden="true" class="svg-icon svg-action-icon">
                                        <use xlink:href="#icon-jiaoyiliushuituikuan"></use>
                                    </svg>
                                </a>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </template>
        </div>
        <div class="trade_money" v-show="showSum">
            <span>{{ $t('trade.totalAmount') }}:</span>
            <span> {{ currency }} {{res.sumMoney | fMoney}}</span>
            <span class="trade_money_span">{{ $t('trade.totalFee') }}:</span>
            <span> {{ currency }} {{res.sumPoundage | fMoney}}</span>
        </div>
        <div class="pagination-container">
            <el-pagination @size-change="handleSizeChange" background @current-change="handleCurrentChange" :current-page.sync="searchOrderData.page" :page-sizes="[15,20,30,50]" :page-size="searchOrderData.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="res.total"></el-pagination>
        </div>

        <!-- 备注 -->
        <el-dialog :title="$t('inputBox.remarks1')" :visible.sync="remarksDialog" custom-class="custom-dialog" :lock-scroll=false :show-close=false width="400px" center :close-on-click-modal=false :modal-append-to-body="true" :append-to-body="true" class="el-dialog-add">
            <div class="box"> {{detail}} </div>
            <span slot="footer" class="dialog-footer remarks_footer">
                <button type="button" @click="remarksDialog = false" class="footer_ok">
                    <span> {{$t('device.OK')}} </span>
                </button>
            </span>
        </el-dialog>

        <!-- 退款 -->
        <el-dialog :title="$t('trade.Refund')" :visible.sync="refundDialog" custom-class="custom-dialog" :lock-scroll=false width="520px" @close="closeRefund" center :close-on-click-modal=false :modal-append-to-body="true" :append-to-body="true" class="el-dialog-add el-dialog-refund">
            <ul class="refund_ul">
                <li>{{$t('trade.TransactionNo')}}：{{outTradeNo}}</li>
                <li>{{$t('trade.Refundable')}}：{{ currency }}{{refundBalance}}</li>
                <li>{{$t('trade.RefundAmount')}}：
                    <div :class="classObj" v-show="refundMoney" :style="{ backgroundColor: bgRefund }">{{ currency }}</div>
                    <input type="text" :disabled="augsStatus" :class="['refund-input',{'clearPD': !refundMoney}]" v-model="refundMoney" maxlength="13" :placeholder="$t('fund.enterAmount')" oninput="this.value=this.value.replace(/[^\d\.]/g,'');if(this.value.includes('.')){if(this.value.split('.')[1].length> 2){this.value=this.value.substring(0,this.value.indexOf('.')+3)}}" />
                    <button class="refund-btn" @click='refundAll' v-show="refundAllStatus">{{ $t('placeH.All') }}</button>
                </li>
            </ul>
            <span slot="footer" class="dialog-footer remarks_footer">
                <el-button :loading="loadingRefund" type="button" @click="refund" class="refund_ok">
                    <span> {{$t('device.OK')}} </span>
                </el-button>
            </span>
        </el-dialog>

        <!-- 进度条 -->
        <el-dialog :title="$t('trade.export')" :visible.sync="exportDialog" custom-class="custom-dialog" :lock-scroll=false center :close-on-click-modal=false :show-close=false :modal-append-to-body="true" :append-to-body="true" class="el-dialog-add el-dialog-progress" :close-on-press-escape=false>
            <el-progress :text-inside="true" :stroke-width="26" :percentage="progressPer"></el-progress>
            <span slot="footer" class="dialog-footer progress_footer">
                <button type="button" @click="perClose()" class="cancel-btn">
                    <span> {{$t('inputBox.cancel')}} </span>
                </button>
            </span>
        </el-dialog>

    </div>
</template>
<script>
import {
    orderAll,
    getDistributors,
    wxRefund,
    wxRefundFindOrder,
    exportExcel
} from "api/orderQuery/index";
import XLSX from "xlsx";
import XLSX_SAVE from "file-saver";
import { Message, MessageBox } from "element-ui";

export default {
    name: "tradingFlow",
    data() {
        return {
            content: "",
            currency: undefined,
            userType: localStorage.getItem("userType"),
            userPhone: localStorage.getItem("phone"),
            tradeDatas: [],
            value: "",
            input: "",
            dialogImageUrl: "",
            dialogVisible: false,
            input: "",
            res: [],
            searchOrderData: {
                outTradeNo: null,
                name: null,
                startDate: null,
                endDate: null,
                minMoney: null,
                maxMoney: null,
                page: 1,
                pageSize: 15,
                subMchId: null,
                shopName: null,
                tradeState: undefined,
                trade: undefined,
                setllment: undefined,
                distributorId: undefined,
                tradeWay: undefined,
                walletType: undefined
            },
            //第一次进订单查询默认展示的数据所需的参数
            orderFormData: {
                page: 1,
                pageSize: 15
            },
            showSubAccountNo: true,
            degIndex: 1,
            rorateFlag: true,
            searchInfo: "",
            tableIndex: "",
            remarksDialog: false,
            detail: "",
            showSum: false,
            companyId: localStorage.getItem("companyId"),
            distributorId: localStorage.getItem("distributorId"),
            firmId: localStorage.getItem("firmId"),
            salesmanId: localStorage.getItem("salesmanId"),
            merchantId: localStorage.getItem("merchantId"),
            grade: localStorage.getItem("grade"),
            userId: localStorage.getItem("access-userId"),
            queryAgentData: [],
            exportSearchData: {},
            refundDialog: false,
            outTradeNo: "",
            refundBalance: "",
            last_td_arr: [],
            refundMoney: "",
            classObj: {
                coinSignEn:
                    localStorage.getItem("locale") == "en" ? true : false,
                coinSign: localStorage.getItem("locale") == "en" ? false : true
            },
            oldPage: null,
            loading: true,
            exportDialog: false,
            progressPer: 0,
            perTimer: null,
            cancelExport: false,
            loadingRefund: false,
            augsStatus: false,
            bgRefund: "#fff",
            refundAllStatus: true,
        };
    },
    watch: {
        refundMoney: function(newVal, oldVal) {
            if (newVal > this.refundBalance) {
                this.refundMoney = this.refundBalance;
            }
        },
        "searchOrderData.page": function(newVal, oldVal) {
            this.oldPage = oldVal;
        }
    },
    created() {
        this.getOrderList(this.orderFormData);
        this.showSubAccountNo = this.userType === "1" ? false : true;
        this.searchInfo = this.$t("trade.MerchantRef1");

        this.searchDistributor();

        if (this.companyId == "1") this.currency = "HK$ ";
        if (this.companyId == "2") this.currency = "A$ ";
    },
    methods: {
        formatFloat(f, digit) { 
            // digit = 2; // 涉及保留两位小数的计算时
            let m = Math.pow(10, digit); 
            let tNum = new Number(parseInt(f * m, 10) / m);
            return tNum; 
        },
        //   关闭进度条
        perClose() {
            const that = this;
            this.$confirm(
                this.$t("hint.Confirmtogiveuptheexport"),
                this.$t("hint.CancelConfirmation"),
                {
                    confirmButtonText: this.$t("button.OK"),
                    cancelButtonText: this.$t("button.Cancel"),
                    showClose: false
                }
            )
                .then(() => {
                    this.exportDialog = false;
                    this.cancelExport = true;
                    this.progressPer = 0;
                    clearInterval(this.perTimer);
                    // 之后重置cancelExport
                })
                .catch(() => {});
        },
        closeRefund() {
            this.refundDialog = false;
            this.refundMoney = "";
        },
        // 退款所有
        refundAll() {
            this.refundMoney = this.refundBalance;
        },
        // 退款弹框
        showRefund(outTradeNo, tradeState, addedDate, outRefundNo, walletType) {
            if (tradeState != "SUCCESS") {
                Message({
                    message: this.$t("trade.CannotRefundUnfinishedTransaction"),
                    type: "error",
                    duration: 5 * 1000
                });
                return;
            }
            let day = new Date().getTime() - new Date(addedDate).getTime();

            if (this.companyId == 2 && (walletType == 0 || walletType == 1)) {
                // 澳洲Augs微信支付
                if (Math.floor(day / 86400000) > 1) {
                    Message({
                        message: this.$t("trade.ExceededRefundablePeriodOf24Hours"),
                        type: "error",
                        duration: 5 * 1000
                    });
                    return;
                }

                this.augsStatus = true; // 禁用金额输入框
                this.bgRefund = "#ebebe4"; // 设置货币层背景色为灰色
                this.refundAllStatus = false; // 将退款所有按钮隐藏

                this.refundDialog = true;
                // 当存在原系统流水号，用原系统流水号，反之用当前交易流水号
                this.outTradeNo = !outRefundNo ? outTradeNo : outRefundNo;
                wxRefundFindOrder(this.outTradeNo).then(res => {
                    if (res.code == 0 && res.value.refundBalance) {
                        this.refundBalance = res.value.refundBalance / 100;
                        this.refundMoney = this.refundBalance; // 将可退所有金额赋值文本框
                    }
                });
            } else {
                if (Math.floor(day / 86400000) > 180) {
                    Message({
                        message: this.$t("trade.ExceededRefundablePeriodOf180Days"),
                        type: "error",
                        duration: 5 * 1000
                    });
                    return;
                }

                this.refundMoney = ""; // 置空金额文本框
                this.augsStatus = false; // 恢复金额输入框为可输入状态
                this.bgRefund = "#fff"; // 设置货币层背景色为白色
                this.refundAllStatus = true; // 将退款所有按钮显示

                this.refundDialog = true;
                // 当存在原系统流水号，用原系统流水号，反之用当前交易流水号
                this.outTradeNo = !outRefundNo ? outTradeNo : outRefundNo;
                wxRefundFindOrder(this.outTradeNo).then(res => {
                    if (res.code == 0 && res.value.refundBalance) {
                        this.refundBalance = res.value.refundBalance / 100;
                    }
                });
            }
        },
        // 退款
        refund() {

            if (this.refundMoney == "" || this.refundMoney == "0") {
                Message({
                    message: this.$t("trade.PleaseEnterRefundAmount"),
                    type: "info",
                    duration: 5 * 1000
                });
                return;
            }

            this.$msgbox({
                title: this.$t("hint.Alert"),
                message: this.$t("hint.confirmRefund") + " " + this.currency + this.refundMoney + " ?",
                showClose: false,
                closeOnClickModal: false,
                showCancelButton: true,
                confirmButtonText: this.$t("button.OK"),
                cancelButtonText: this.$t("button.Cancel"),
                beforeClose: (action, instance, done) => {
                    if (action == "confirm") {
                        this.loadingRefund = true;
                        wxRefund({
                            outTradeNo: this.outTradeNo,
                            money: this.formatFloat(Number(this.refundMoney) * 10000/100,2),
                            merchantId: this.merchantId,
                            userId: this.userId
                        }).then(res => {
                            this.loadingRefund = false;
                            this.refundMoney = "";
                            if (res.code == 0) {
                                this.handleFilter(1);
                                this.refundDialog = false;
                                this.$notify({
                                    title: this.$t("hint.Success"),
                                    message: this.$t("hint.OperationSuccess"),
                                    type: "success",
                                    duration: 2000
                                });
                            } else if (res.code == 119) {
                                Message({
                                    message: this.$t(
                                        "trade.InsufficientBalanceForThisRefund"
                                    ),
                                    type: "error",
                                    duration: 5 * 1000
                                });
                            } else if (res.code == 112) {
                                Message({
                                    message: this.$t("trade.ExceededMaximum50Refunds"),
                                    type: "error",
                                    duration: 5 * 1000
                                });
                            } else {
                                Message({
                                    message: this.$t("hint.OperationFail"),
                                    type: "error",
                                    duration: 5 * 1000
                                });
                            }
                        }).catch(err=>{
                            this.loadingRefund = false;
                            Message({
                                message: this.$t("hint.OperationFail"),
                                type: "error",
                                duration: 5 * 1000
                            });
                        });
                    }
                    done();
                }
            });

        },
        // 获得代理商下拉框的数据
        searchDistributor() {
            let searchData = {};

            if (this.userType == 2 && this.grade > 0) {
                searchData.distributorId = this.distributorId;
            } else if (
                this.userType == 5 ||
                this.userType == 9 ||
                this.grade == 0 ||
                this.userType == 0 ||
                this.userType == 11
            ) {
                searchData.companyId = this.companyId;
            } else if (this.userType == 10) {
                searchData.firmId = this.firmId;
            } else if (this.userType == 8) {
                searchData.salesmanId = this.salesmanId;
            } else if (this.userType == 1) {
                searchData.merchantId = this.merchantId;
            }

            getDistributors(searchData)
                .then(res => {
                    if (res.code == 0) {
                        // console.log("查询所属代理商返回数据：" + res);
                        this.queryAgentData = res.value;
                        // this.queryAgentData = res.value.filter(function(item,index,array){
                        //     return (item.grade != 0);
                        // })
                    }
                })
                .catch(() => {});
        },
        //显示备注
        showRemarks(detail) {
            this.remarksDialog = true;
            this.detail =
                detail === undefined || detail === null || detail === ""
                    ? ""
                    : detail;
        },
        showHandle(row, column, cell, event) {
            // console.log(row);
            for (let i = 0; i < this.tradeDatas.length; i++) {
                if (this.tradeDatas[i].orderId === row.orderId) {
                    this.tableIndex = i;
                    const table_row = $(".el-table__fixed-right").find(
                        ".el-table__row"
                    )[i];
                    $(table_row)
                        .find("td:last")
                        .removeClass("handle-hidden-" + this.last_td_arr[i]);
                    $(".el-table__fixed-right").addClass(
                        "fixed-column-" + this.last_td_arr[i]
                    );
                    $(".el-table__fixed-right").css("z-index", "22");
                    var action_div = $(table_row)
                        .find("td:last")
                        .children("div");
                    // $(action_div).css("right","-360px");
                    $(action_div)
                        .stop()
                        .animate({ right: "0" });
                }
            }
            // 判断项目数目是否导致滚动条出现
            if (this.tradeDatas.length <= 15) {
                $(".el-table__fixed-right").addClass("right-zero");
            } else {
                $(".el-table__fixed-right").removeClass("right-zero");
            }
        },
        hiddenHandle(row, column, cell, event) {
            const table_row = $(".el-table__fixed-right").find(
                ".el-table__row"
            )[this.tableIndex];
            $(".el-table__fixed-right").css("z-index", "0");
            var action_div = $(table_row)
                .find("td:last")
                .children("div");
            $(action_div)
                .stop()
                .animate({ right: "-240px" });
        },
        //刷新数据
        refresh() {
            const _that = this;
            if (this.rorateFlag) {
                document.getElementById("refresh_icon").style.transform =
                    "rotate(" + this.degIndex * 360 + "deg)";
                this.handleFilter(1);
                this.rorateFlag = false;
                setTimeout(function(param) {
                    _that.rorateFlag = true;
                    _that.degIndex++;
                }, 1000);
            }
        },
        // 格式化店铺名
        judgeShopName(row) {
            let shop = row.shopName;
            if (shop == "" || !shop) {
                return (shop = "-");
            }
            return shop;
        },
        // 格式化通道
        judgeTradeWay(row) {
            // 改成支付宝与微信支付
            let way = row.walletType;
            if (way == 0) {
                return (way = this.$t("search.WechatRMBWallet"));
            }
            if (way == 1) {
                return (way =
                    this.companyId == "2"
                        ? this.$t("search.WechatRMBWallet")
                        : this.$t("search.WechatHKDWallet"));
            }
            //   if( way == 2 ){
            //     return way = this.companyId == '2' ? this.$t("search.Alipay") : this.$t("search.AlipayHK");
            //   }
            if (way == 3 || way == 2) {
                return (way = this.$t("search.Alipay"));
            }
            if (way == 4) {
                return (way = this.$t("trade.Unionpay"));
            }
        },
        judgeOutRefundNo(row) {
            let outRefundNo = row.outRefundNo;
            if (outRefundNo) {
                return (outRefundNo = row.outRefundNo);
            } else {
                return (outRefundNo = "-");
            }
        },
        judgeTransactionNo(row) {
            if(!row.no) {
                return "-";
            } else {
                return row.no;
            }
        },
        //交易结果
        judgePayResult(row) {
            let payResult = row.tradeState;
            return (payResult =
                payResult === "SUCCESS"
                    ? this.$t("search.Yes")
                    : this.$t("search.No"));
        },
        //设备
        judgeDevice(row) {
            let device = row.deviceType;
            if( device == undefined ) {
                return (device = '-');
            }
            if (device === "0") {
                return (device = this.$t("inputBox.QRcode"));
            }
            if (device === "1") {
                return (device = this.$t("inputBox.scanner"));
            }
            if (device === "2") {
                return (device = this.$t("trade.AppPay"));
            }
            if (device === "3") {
                return (device = this.$t("trade.SubordinateMerchant"));
            }
        },
        // 格式化设备编号
        judgeDeviceNo(row) {
            let deviceNo = row.deviceNo;
            if (deviceNo == "0000001" || !deviceNo) {
                return (deviceNo = "-");
            }
            return deviceNo;
        },
        //结算状态
        judgeSetllment(row) {
            let formatSetllment = row.setllment;
            if ( row.walletType == 1 || row.walletType == 3 || row.walletType == 4 ) {
                return formatSetllment = "-";
            }
            if (formatSetllment == 0) {
                return (formatSetllment = this.$t("search.NotSettled"));
            }
            if (formatSetllment == 1) {
                return (formatSetllment = this.$t("search.SettledDone"));
            }
        },
        // 格式化操作员
        judgeStaff(row) {
            let staff = row.cashierName;
            if (staff == "" || !staff) {
                return (staff = "-");
            }
            return staff;
        },
        //支付方式
        judgePayMethod(row) {
            let showType = row.payType;
            // 微信
            if (showType == "11") {
                return (showType = this.$t("search.SweepPay"));
            }
            if (showType == "12") {
                return (showType = this.$t("search.WeChatPayScan"));
            }
            if (showType == "13") {
                return (showType = this.$t("search.OAPayment"));
            }
            if (showType == "14") {
                return (showType = this.$t("trade.AppPay"));
            }
            if (showType == "15") {
                return (showType = this.$t("trade.MiniProgram"));
            }

            // 支付宝
            if (showType == "21") {
                return (showType = this.$t("search.SweepPay"));
            }
            if (showType == "22") {
                return (showType = this.$t("search.ScanPay"));
            }

            // 银联
            if (showType == "24") {
                return (showType = this.$t("trade.H5Payment"));
            } else {
                return showType = "-";
            }
        },
        //格式化实收金额
        judgeCollected(row) {
            let formatCollected = row.collectedAmount;
            return (formatCollected =
                this.currency + this.fmoney(formatCollected, 2));
        },
        //格式化手续费
        judgePoundage(row) {
            let formatPoundage = row.poundage;
            if (row.tradeState === "SUCCESS") {
                return (formatPoundage =
                    this.currency + this.fmoney(formatPoundage, 2));
            } else {
                return (formatPoundage = this.currency + "0.00");
            }
        },
        //格式化提现金额
        judgeMoney(row) {
            let formatMoney = row.money;
            return (formatMoney = this.currency + this.fmoney(formatMoney, 2));
        },
        // 格式化金额
        fmoney(s, n) {
            if (s === "" || s === undefined) return (s = "0.00");
            s = s / 100;
            n = n > 0 && n <= 20 ? n : 2;
            s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
            var l = s
                    .split(".")[0]
                    .split("")
                    .reverse(),
                r = s.split(".")[1];
            let t = "";
            for (let i = 0; i < l.length; i++) {
                t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
            }
            return (
                t
                    .split("")
                    .reverse()
                    .join("") +
                "." +
                r
            );
        },
        //格式化交易类型
        judgePayType(row) {
            let formatPayType = row.payType;
            let way = row.walletType; // 判断是不是支付宝
            if (way == 2 || way == 3) {
                return (formatPayType = formatPayType === "33" ? this.$t("trade.Refund") : this.$t("trade.Payment"));
            } else if( way == 4 ) {
                return (formatPayType = formatPayType === "34" ? this.$t("trade.Refund") : this.$t("trade.Payment"));
            } else {
                return (formatPayType = formatPayType === "32" ? this.$t("trade.Refund") : this.$t("trade.Payment"));
            }
        },
        open(state) {
            const h = this.$createElement;
            this.$msgbox({
                title: this.$t("hint.Alert"),
                message: this.$t("hint.SureToSuspendThisMerchant"),
                showClose: false,
                showCancelButton: true,
                confirmButtonText: this.$t("button.OK"),
                cancelButtonText: this.$t("button.Cancel"),
                beforeClose: (action, instance, done) => {
                    done();
                }
            });
        },
        getOrderList(value, str) {
            const _that = this;
            this.last_td_arr = [];
            value.companyId = this.companyId;
            //				value.distributorId = localStorage.getItem('distributorId');
            orderAll(value)
                .then(res => {
                    // console.log("订单查询返回的数据");
                    // console.log(res);
                    this.res = res.value;
                    this.showSum = true;
                    this.tradeDatas = res.value.list;
                    for (let i = 0; i < this.tradeDatas.length; i++) {
                        if (this.tradeDatas[i].tradeState == "SUCCESS") {
                            this.tradeDatas[i].collectedAmount =
                                this.tradeDatas[i].money -
                                this.tradeDatas[i].poundage;
                        } else {
                            this.tradeDatas[i].collectedAmount = 0;
                        }
                    }

                    // 如果是分页触发，循环去除选中样式，对点击后的项数添加选中样式
                    if (str == "CurrentChange") {
                        let obj = $(".el-pager .number");
                        for (let i = 0; i < obj.length; i++) {
                            if ($(obj[i]).html() == this.searchOrderData.page) {
                                $(obj[i]).addClass("active");
                            } else {
                                $(obj[i]).removeClass("active");
                            }
                        }
                    }

                    setTimeout(function(param) {
                        const td_last_child = $(
                            ".el-table__body-wrapper tr td:last-child"
                        );
                        for (let i = 0; i < td_last_child.length; i++) {
                            $(td_last_child[i]).removeClass("handle-hidden-2");
                        }
                        const td_fixed_last_child = $(
                            ".el-table__fixed-right tr td:last-child"
                        );
                        for (let i = 0; i < td_fixed_last_child.length; i++) {
                            _that.last_td_arr.push(
                                $(td_fixed_last_child[i]).find(
                                    ".svg-link-class"
                                ).length
                            );
                            if (
                                $(td_fixed_last_child[i]).find(
                                    ".svg-link-class"
                                ).length == 1
                            ) {
                                $(td_fixed_last_child[i])
                                    .removeClass("handle-hidden-3")
                                    .removeClass("handle-hidden-2")
                                    .addClass("handle-hidden-1");
                            } else if (
                                $(td_fixed_last_child[i]).find(
                                    ".svg-link-class"
                                ).length == 2
                            ) {
                                $(td_fixed_last_child[i])
                                    .removeClass("handle-hidden-3")
                                    .removeClass("handle-hidden-1")
                                    .addClass("handle-hidden-2");
                            }
                        }
                        const title_name_arr = $(
                            ".el-table__body-wrapper .title_name .cell"
                        );
                        for (let j = 0; j < title_name_arr.length; j++) {
                            $(title_name_arr[j]).attr(
                                "title",
                                $(title_name_arr[j]).html()
                            );
                        }

                        // 隐藏载入提示层
                        _that.loading = false;
                    }, 500);
                })
                .catch(error => {
                    console.log(error);
                });
        },
        // 判断字符串长度的方法
        getStrL(str) {
            let l = str.length;
            let blen = 0;
            for (let i = 0; i < l; i++) {
                if ((str.charCodeAt(i) & 0xff00) != 0) {
                    blen++;
                }
                blen++;
            }
            return blen;
        },
        delSelect() {
            this.searchOrderData.outTradeNo = null;
            this.searchOrderData.name = null;
            this.searchOrderData.startDate = null;
            this.searchOrderData.endDate = null;
            this.searchOrderData.minMoney = null;
            this.searchOrderData.maxMoney = null;
            this.searchOrderData.subMchId = null;
            this.searchOrderData.shopName = null;
            this.searchOrderData.distributorId = null;
            this.searchOrderData.trade = null;
            this.searchOrderData.tradeState = null;
            this.searchOrderData.walletType = null;
            this.searchOrderData.setllment = null;
            this.searchOrderData.page = 1;
            this.searchOrderData.pageSize = 15;
            this.searchInfo = this.$t("trade.MerchantRef1");
            this.handleFilter(1);
        },
        //点击搜索 查询订单
        handleFilter(sign, str) {
            // 显示载入提示层
            this.loading = true;

            // sign 0 搜索 1其他
            if (sign === 0) this.searchInfo = this.$t("index.searchResults");

            // 判断最大小值是否填写，若最小值最大值大小相反，调整赋值
            if (
                this.searchOrderData.minMoney != null &&
                this.searchOrderData.minMoney != "" &&
                this.searchOrderData.maxMoney != null &&
                this.searchOrderData.maxMoney != ""
            ) {
                if (
                    parseInt(this.searchOrderData.minMoney) >
                    parseInt(this.searchOrderData.maxMoney)
                ) {
                    [
                        this.searchOrderData.minMoney,
                        this.searchOrderData.maxMoney
                    ] = [
                        this.searchOrderData.maxMoney,
                        this.searchOrderData.minMoney
                    ];
                }
            }

            //查询商户的参数
            this.exportSearchData = {};
            $.extend(this.exportSearchData, this.searchOrderData);
            this.formatObj(this.exportSearchData);
            if (this.exportSearchData.minMoney)
                this.exportSearchData.minMoney = Math.ceil(
                    this.exportSearchData.minMoney * 100
                );
            if (this.exportSearchData.maxMoney)
                this.exportSearchData.maxMoney = Math.ceil(
                    this.exportSearchData.maxMoney * 100
                );
            // console.log("设备查询向后台发送的数据");
            // console.log(searchOrderData);
            this.getOrderList(this.exportSearchData, str);

            if (str == "CurrentChange") {
                // 获取所有分页项数，循环去除选中样式，对点击前的项数添加选中样式
                let obj = $(".el-pager .number");
                for (let i = 0; i < obj.length; i++) {
                    if ($(obj[i]).html() == this.oldPage) {
                        $(obj[i]).addClass("active");
                    } else {
                        $(obj[i]).removeClass("active");
                    }
                }
            }
        },
        //pageSize 改变时会触发
        handleSizeChange(val) {
            this.searchOrderData.pageSize = val;
            this.handleFilter(1);
        },
        //currentPage 改变时会触发
        handleCurrentChange(val) {
            this.searchOrderData.page = val;
            this.handleFilter(1, "CurrentChange");
        },
        //导出表格
        export2Excel() {
            const that = this;
            this.exportDialog = true;
            this.cancelExport = false;
            this.perTimer = setInterval(function() {
                if (that.progressPer >= 89) {
                    that.progressPer == that.progressPer;
                } else {
                    that.progressPer += parseInt(Math.ceil(10 * Math.random()));
                }
            }, 500);
            let listQuery = {};
            let length = this.res.total;
            $.extend(listQuery, this.exportSearchData);
            listQuery.pageSize = length;
            listQuery.page = 1;
            listQuery.companyId = this.companyId;
            listQuery.locale = localStorage.getItem("locale");
            if (this.companyId == 2 && this.userType == 5) {
                listQuery.fsExcel = 1;
            } else if (
                this.companyId == 1 &&
                (this.userType == 11 ||
                    this.userType == 9 ||
                    this.userPhone === "13501189583" ||
                    this.userPhone === "15018955912" ||
                    this.userPhone === "15219441946")
            ) {
                listQuery.fsExcel = 1;
            } else {
                listQuery.fsExcel = 0;
            }
            exportExcel(listQuery).then(res => {
                that.progressPer = 100;
                setTimeout(function() {
                    let url = window.URL.createObjectURL(new Blob([res]));
                    let link = document.createElement("a");
                    link.style.display = "none";
                    link.href = url;
                    link.setAttribute(
                        "download",
                        that.$t("index.MerchantOrders")
                    );
                    document.body.appendChild(link);

                    if (that.cancelExport) {
                        console.log("取消导出");
                    } else {
                        link.click();
                    }
                    link.parentNode.removeChild(link);

                    that.exportDialog = false;
                    that.progressPer = 0;
                    clearInterval(that.perTimer);
                }, 1000);
            });
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]));
        },
        formatObj(obj) {
            let arr = Object.keys(obj);
            for (let i = 0; i < arr.length; i++) {
                if (obj[arr[i]] === "") {
                    obj[arr[i]] = null;
                }
            }
        }
    }
};
</script>

<style lang="scss" scoped>
.box {
    height: 200px;
    width: 300px;
    border-radius: 8px;
    border: 1px solid #5272e9;
    margin: 0 auto;
    padding: 8px 15px;
    word-break: break-word;
}
.remarks_footer {
    padding-bottom: 20px;
    .footer_ok {
        background: #5272e9;
        border-radius: 8px;
        border: none;
        color: #fff;
        width: 200px;
        height: 48px;
        font-size: 24px;
        font-weight: normal;
        margin-top: -32px;
        margin-bottom: 10px;
        outline: none;
    }
}
.trade_money {
    margin-top: 10px;
    color: black;
    font-weight: bold;
    padding-left: 20px;
    font-style: italic;
    .trade_money_span {
        margin-left: 30px;
    }
}
.refund_ul {
    margin: 0;
    padding: 0 30px;
    li {
        margin: 15px 0;
        color: #333;
    }
    li:first-child {
        margin-bottom: 23px;
    }
    li:last-child {
        position: relative;
        .coinSign {
            position: absolute;
            left: 80px;
            top: 6px;
            width: 31px;
            height: 24px;
            line-height: 23px;
            background-color: #fff;
            font-weight: bold;
            text-align: center;
        }
        .coinSignEn {
            position: absolute;
            left: 122px;
            top: 6px;
            width: 31px;
            height: 24px;
            line-height: 23px;
            background-color: #fff;
            font-weight: bold;
            text-align: center;
        }
    }
    .refund-input {
        width: 190px;
        height: 35px;
        border: 1px solid rgba(215, 215, 215, 1);
        border-radius: 2px;
        outline: none;
        font-weight: bold;
        padding: 0 0 0 38px;
        margin: 0;
    }
    .clearPD {
        padding: 0 0 0 10px;
    }
    .refund-btn {
        width: 52px;
        height: 35px;
        border: 1px solid rgba(215, 215, 215, 1);
        border-radius: 2px;
        margin-left: -5px;
        color: #5272e9;
        font-weight: 500;
        background: rgba(255, 255, 255, 1);
        outline: none;
        vertical-align: bottom;
    }

    .refund-input::-webkit-input-placeholder {
        color: #c0c4cc;
        font-weight: normal;
    }
    .refund-input::-moz-placeholder {
        /* Mozilla Firefox 19+ */
        color: #c0c4cc;
        font-weight: normal;
    }
    .refund-input:-moz-placeholder {
        /* Mozilla Firefox 4 to 18 */
        color: #c0c4cc;
        font-weight: normal;
    }
    .refund-input:-ms-input-placeholder {
        /* Internet Explorer 10-11 */
        color: #c0c4cc;
        font-weight: normal;
    }
}
.refund_ok {
    background: #5272e9;
    border-radius: 8px;
    border: none;
    color: #fff;
    width: 160px;
    height: 40px;
    font-size: 16px;
    font-weight: normal;
    margin-top: -32px;
    // margin-bottom: 10px;
    outline: none;
}
input.refund-input::-webkit-input-placeholder {
    color: #333;
}
.refund_ok:hover {
    background-color: #355be6;
}

.progress_footer {
    padding-bottom: 30px;
    .cancel-btn {
        background: #fff;
        border-radius: 8px;
        border: none;
        color: #5272e9;
        width: 160px;
        height: 34px;
        font-size: 16px;
        font-weight: normal;
        margin-top: -32px;
        outline: none;
        border: 1px solid #5272e9;
        transition: 0.3s all;
        &:hover {
            background-color: #5272e9;
            color: #fff;
        }
    }
}
</style>